package com.rc.saas.tenant.component;

import com.github.pagehelper.util.StringUtil;
import com.rc.saas.tenant.common.utils.AliyunOssUtil;
import com.rc.saas.tenant.common.utils.FileHandler;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.upyun.WebUploader;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;

/**
 * @author frog
 * @date 2021/5/25
 */
@Component
public class UploadComponent {

    @Autowired
    private UpYunConfig upYunConfig;

    /**
     * 上传图片
     * @param uploadFile
     * @return
     */
    public String uploadFile(String tenantCode, MultipartFile uploadFile) {

        if (uploadFile == null) {
            return null;
        }
        WebUploader webUploader = WebUploader.getInstance(upYunConfig);
        String uploadFileName = null;
        try {
            uploadFileName = uploadFile(tenantCode, webUploader, uploadFile, null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (StringUtils.isBlank(uploadFileName)) {
            return null;
        }

        return uploadFileName;
    }


    /**
     * 上传到CDN，并返回存储的路径
     *
     * @param webUploader
     * @param file
     * @return
     */
    public String uploadFile(String tenantCode, WebUploader webUploader, MultipartFile file, String fileType) {

        if (org.apache.commons.lang3.StringUtils.isEmpty(tenantCode)) {
            tenantCode = "356451769";
        }
        String uploadFileName = tenantCode + upYunConfig.getUploadImagePath();
        if (StringUtil.isNotEmpty(fileType)) {
            uploadFileName = tenantCode + fileType;
        }
        uploadFileName = uploadFileName + FileHandler.createFileNameByTimeRole(file.getOriginalFilename());

        String url = AliyunOssUtil.FilePut(file, uploadFileName);
        if (url != null) {
            return url;
        } else {
            return null;
        }
    }

    public boolean deleteFile(String path) {
        try {
            AliyunOssUtil.deletePut(path);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String rootPath() {
        return upYunConfig.getDownloadRoot();
    }
}
